package com.topisv.tms.service.stock.outstorage;

import java.text.DecimalFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.stock.oustorage.OutstorageBill;
import com.topisv.tms.entity.stock.oustorage.OutstorageBox;
import com.topisv.tms.entity.stock.oustorage.OutstorageBoxItem;
import com.topisv.tms.entity.stock.oustorage.OutstorageSendTask;
import com.topisv.tms.repository.stock.outstorage.OutstorageBillDao;
import com.topisv.tms.repository.stock.outstorage.OutstorageBoxDao;
import com.topisv.tms.repository.stock.outstorage.OutstorageBoxItemDao;
import com.topisv.tms.repository.stock.outstorage.OutstorageSendTaskDao;

/**
 * 出库箱_service
 * @author ch
 *
 */
@Component
@Transactional(readOnly = true)
public class OutstorageBoxService {
	
	@Autowired
	private OutstorageBoxDao outstorageBoxDao;
	@Autowired
	private OutstorageBillDao outstorageBillDao;
	@Autowired
	private OutstorageSendTaskDao outstorageSendTaskDao;
	@Autowired
	private OutstorageBoxItemDao  outstorageBoxItemDao;

	/**
	 * 创建出库箱
	 * @param taskCode 发货任务编号
	 * @return
	 * @throws Exception 
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public String createBox(String taskCode) throws Exception {
		try {
			OutstorageSendTask task=this.outstorageSendTaskDao.loadByTaskCode(taskCode);
			OutstorageBill bill=this.outstorageBillDao.loadByBillCode(task.getBillCode());
			DecimalFormat df=new DecimalFormat("000000");
			
			//修改发货任务状态
			task.setStatus("doing");
			this.outstorageSendTaskDao.save(task);
			
			//创建出库箱
			OutstorageBox box=new OutstorageBox();
			box.setBillCode(bill.getBillCode());
			this.outstorageBoxDao.save(box);
			
			//设置箱条码
			Long id=box.getId();
			String boxCode=bill.getWarehouseOutCode()+"-"+bill.getWarehouseInCode()+"-"+df.format(id);
			box.setBoxCode(boxCode);
			this.outstorageBoxDao.save(box);
			
			return boxCode;
		
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 删除箱子
	 * @param boxCode
	 * @throws Exception 
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void delBox(String boxCode) throws Exception {
		try {
			
			//删除箱子
			OutstorageBox box=this.outstorageBoxDao.loadByBoxCode(boxCode);
			this.outstorageBoxDao.delete(box);
			
			
			//删除箱子明细
			List<OutstorageBoxItem> itemList=this.outstorageBoxItemDao.loadByBoxCode(boxCode);
			this.outstorageBoxItemDao.delete(itemList);
			
			
		} catch (Exception e) {
			throw e;
		}
	}

}
